package com.spzx.order.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.domain.CartItem;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.dto.OrderSubmitDTO;
import com.spzx.order.domain.vo.TradeVO;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.service.IOrderItemService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.domain.SkuPriceDTO;
import com.spzx.product.domain.SkuStockDTO;
import com.spzx.common.rabbitmq.cons.SpzxMqCons;
import com.spzx.common.rabbitmq.service.RabbitmqService;
import com.spzx.user.api.RemoteUserService;
import com.spzx.user.domain.UserAddress;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.service.IOrderInfoService;
import org.springframework.util.CollectionUtils;

/**
 * 订单Service业务层处理
 *
 * @author atguigu
 * @date 2024-10-04
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService
{
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    private RemoteProductService remoteProductService;


    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Resource
    private RemoteCartService remoteCartService;

    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private IOrderItemService iOrderItemService;

    @Resource
    private RabbitmqService rabbitmqService;

    /**
     *
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo)
    {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }


    @Override
    public OrderInfo selectOrderInfoById(Long id)
    {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public TradeVO trade() {

        //1、从购物车中查询当前用户的
        Long userId = SecurityUtils.getUserId();
        R<List<CartItem>> listR = remoteCartService.listCheckedCartItems(userId);

        if (listR.getCode()!=200){
            throw new ServiceException("远程调用cart服务失败"+listR.getMsg());
        }
        List<CartItem> cartItemList = listR.getData();

        //转换为订单列表
        List<OrderItem> orderItems = cartItemList.stream().map(cartItem -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartItem.getSkuId());
            orderItem.setSkuName(cartItem.getSkuName());
            orderItem.setThumbImg(cartItem.getThumbImg());
            //购物车的商品实时价格同步 使用商品的实时价格计算
            orderItem.setSkuPrice(cartItem.getSkuPrice());
            orderItem.setSkuNum(cartItem.getSkuNum() + 0L);
            return orderItem;
        }).collect(Collectors.toList());

        BigDecimal totalAmount = orderItems.stream().map(orderItem -> orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())))
                .reduce((a, b) -> a.add(b)).get();
        //2、根据购物项   生成结算数据
        //一个用户一个购物车，一个购物车多个购物项(一个购物项对应一个sku)
        //结算时： 一个用户购物车中选中的购

        TradeVO tradeVO = new TradeVO();
        tradeVO.setTotalAmount(totalAmount);
        tradeVO.setOrderItemList(orderItems);

        return tradeVO;

    }

    @Override
    public Long submitOrder(OrderSubmitDTO orderSubmitDTO) {
        //保证幂等性 ： 防止 同一个页面 多次提交 创建 多个订单
        String tradeNo = orderSubmitDTO.getTradeNo();
        //tradeNo做键  值随便给  有效时间10分钟
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(tradeNo, "1", 10, TimeUnit.MINUTES);
        if (!flag){
            //重复提交了 抛出异常
            throw new ServiceException("订单重复提交");
        }
        //2、检验金额 ： 防止商品价格变动
        //前端提交的订单项的总金额 和 商品金额 进行比较

        //通过远程调用 检验价格
        //将前端传入的提交的DTO封装给skuPriceDTOs
        List<SkuPriceDTO> skuPriceDTOS = orderSubmitDTO.getOrderItemList().stream().map(orderItem -> {
            SkuPriceDTO skuPriceDTO = new SkuPriceDTO();
            skuPriceDTO.setSkuPrice(orderItem.getSkuPrice());
            skuPriceDTO.setSkuName(orderItem.getSkuName());
            skuPriceDTO.setSkuId(orderItem.getSkuId());
            return skuPriceDTO;
        }).collect(Collectors.toList());


        //远程调用 校验价格
        R<List<SkuPriceDTO>> checkSkusPriceR = remoteProductService.checkSkusPrice(skuPriceDTOS);
        if (checkSkusPriceR.getCode()!=200){
            throw new ServiceException("商品价格校验异常");
        }

        //校验后的结果
        skuPriceDTOS = checkSkusPriceR.getData();

        //校验失败的集合
        List<SkuPriceDTO> checkPriceFailDtos = skuPriceDTOS.stream().filter(skuPriceDTO -> !skuPriceDTO.getFlag()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(checkPriceFailDtos)){
            //拼接验价失败的商品的标题
            String skuNames = checkPriceFailDtos.stream().map(checkPriceFailDTO -> checkPriceFailDTO.getSkuName())
                    .reduce((name1, name2) -> name1 + "," + name2).get();
            //存在验价失败的商品列表
            throw new ServiceException("页面数据过期，商品 "+skuNames+" 价格变动，请刷新页面");
        }

        //3、验库存锁库存：
    /*
        是否允许商品超卖：
            1、不允许超卖：  数据库表库存字段设置UNSIGNED 无符号的，不能为负数 ， 业务中验库存锁库存保证原子性 性能较差
                下单前 需要原子性验库存锁库存，只有成功的才可以创建订单
            2、允许适量超卖：
                    只是在下单时 验一下库存是否足够
                    用户支付成功 才减库存
            3、允许超卖：不考虑库存是否为负数
     */


        //将传输过来的库存数据封装 并远程调用 检验库存
        List<SkuStockDTO> stockDTOS = orderSubmitDTO.getOrderItemList().stream()
                .map(orderItem -> {
                    SkuStockDTO skuStockDTO = new SkuStockDTO();
                    skuStockDTO.setSkuId(orderItem.getSkuId());
                    skuStockDTO.setSkuNum(orderItem.getSkuNum());
                    skuStockDTO.setSkuName(orderItem.getSkuName());
                    return skuStockDTO;
                }).collect(Collectors.toList());

        //3.2 远程访问product服务 对每个商品进行验库存锁库存的操作
        //  验库存锁库存时，只要有一个失败 全部都失败   全部成功才成功   必须数据安全
        R<List<SkuStockDTO>> skusStockR = remoteProductService.checkSkusStock(stockDTOS);
        if(skusStockR.getCode()!=200){
            throw new ServiceException("商品库存校验异常");
        }
        stockDTOS = skusStockR.getData();
        //获取锁定失败的库存信息
        List<SkuStockDTO> lockedFailStockDTOS = stockDTOS.stream()
                .filter(skuStockDTO -> !skuStockDTO.getFlag()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(lockedFailStockDTOS)){
            //有锁库存失败的商品
            String skuNames = lockedFailStockDTOS.stream().map(skuStockDTO -> skuStockDTO.getSkuName())
                    .reduce((a, b) -> a + "," + b).get();
            throw new ServiceException("商品 "+ skuNames +" 库存不足");
        }

        //4、创建订单保存
        R<UserAddress> userAddressR = remoteUserService.getUserAddressById(orderSubmitDTO.getUserAddressId());
        if (userAddressR.getCode()!=200){
            throw new ServiceException("远程调用根据id获取用户地址失败"+userAddressR.getMsg());

        }

        String orderNo = UUID.fastUUID().toString();
        UserAddress userAddress = userAddressR.getData();
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(SecurityUtils.getUserId());
        orderInfo.setNickName(SecurityUtils.getUsername());
        orderInfo.setOrderNo(orderNo);

        //orderSubmitDTO
        BigDecimal bigDecimal = orderSubmitDTO.getOrderItemList()
                .stream()
                .map(orderItem -> orderItem.getSkuPrice()
                        .multiply(new BigDecimal(orderItem.getSkuNum()))).reduce((a, b) -> a.add(b)).get();

        //查询用户地址信息
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getAddress());
        baseMapper.insert(orderInfo);


        //5、创建订单项 关联订单
        Long orderId = orderInfo.getId();
        orderSubmitDTO.getOrderItemList().forEach(orderItem -> {
            orderItem.setOrderId(orderId);
        });

        /*
        *删除购物车中使用过的购物项
        *
            异步解耦合：
                Rabbitmq：
                    订单创建成功 发送mq消息
                    购物车服务可以创建消费者监听消息，一旦订单创建成功 可以删除购物车中选中的购物项
        * */

        //发送一个订单创建成功的消息，购物车服务可以通过消费者消费消息：执行删除购物项业务
        // 购物车服务使用 userId就可以删除  但是其他业务也可能会使用该消息
        //  消息可以携带userId，orderNo,orderId , totalAmount
        Map<String ,Object> messageMap = new HashMap<>();
        messageMap.put("userId" , orderInfo.getUserId());
        messageMap.put("orderNo" , orderInfo.getOrderNo());
        messageMap.put("orderId" , orderInfo.getId());
        messageMap.put("totalAmount" , orderInfo.getTotalAmount());

        rabbitmqService.sendMsg(SpzxMqCons.ORDER_EXCHANGE,
                SpzxMqCons.ORDER_SUBMIT_ROUTING_KEY, messageMap);






            iOrderItemService.saveBatch(orderSubmitDTO.getOrderItemList());
        return orderId;
    }
}
